<?php
/**
*
* @package phpBB3
* @version $Id: chat.php 52 2007-11-04 05:56:17Z Handyman $
* @copyright (c) 2007 StarTrekGuide
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*
*/

/**
* @ignore
*/
$chat_php = $_SERVER['PHP_SELF'];

if ($chat_php == '/chat.php')
{
define('IN_PHPBB', true);
$phpbb_root_path = './';
$phpEx = substr(strrchr(__FILE__, '.'), 1);
include($phpbb_root_path . 'common.' . $phpEx);
include($phpbb_root_path . 'includes/functions_display.' . $phpEx);
}
include($phpbb_root_path . 'includes/functions_posting.' . $phpEx);
include($phpbb_root_path . 'includes/functions_chat.' . $phpEx);

// Start session management
$user->session_begin();
$auth->acl($user->data);
$user->setup('mods/chat_mod');
$user->add_lang('posting');

$chat = new chat();
$chat_config = $chat->get_chat_config();

$chat->check_errors();

$popup = request_var('popup', '');
$popup_enabled = $chat_config['chat_popup_enabled'];

$template->assign_vars(array(
	'S_CHAT_POPUP_ENABLED'		=> ($popup_enabled == 1) ? true : false,
));

/******************************************/
/* EDIT these for custom online settings */
/****************************************/
$session_time = 300;  // Does anyone know what this is for?

/*****************************************/
/* DO NOT EDIT ANYTHING BELOW THIS LINE */
/***************************************/
$default_delay = $chat_config['update_seconds'];
//set status
$times = array(
	'online'	=> $chat_config['online_time'],
	'idle'		=> $chat_config['idle_time'],
	'offline'	=> $chat_config['offline_time'],
);
//set delay for each status
$delay = array(
	'online'	=> $chat_config['online_delay'],
	'idle'		=> $chat_config['idle_delay'],
	'offline'	=> $chat_config['offline_delay'],
);

$mode = request_var('mode', '');
$last_id = request_var('last_id', 0);
$last_post = request_var('last_post', 0);
$last_time = request_var('last_time', 0);
$get = $init = false;
$count = 0;

$channel_var = request_var('cid', 0);
$channel_id = ($channel_var) ? $channel_var : 1;

switch ($mode)
{
	default:
		$sql = 'SELECT * FROM ' . CHAT_TABLE . '
			WHERE channel_id = ' . $channel_id . '
			ORDER BY message_id DESC';
		$result = $db->sql_query_limit($sql, $chat_config['num_message_display']);
		$rows = $db->sql_fetchrowset($result);

		foreach ($rows as $row)
		{
			if ($count++ == 0)
			{
				$last_id = $row['message_id'];
			}
			$template->assign_block_vars('chatrow', array(
				'MESSAGE_ID'	=> $row['message_id'],
				'USERNAME_FULL'	=> get_username_string('full', $row['user_id'], $row['username'], $row['user_colour'], $user->lang['GUEST']),
				'MESSAGE'		=> generate_text_for_display($row['message'], $row['bbcode_uid'], $row['bbcode_bitfield'], $row['bbcode_options']),
				'TIME'			=> $user->format_date($row['time']),
				'CLASS'			=> ($row['message_id'] % 2) ? 1 : 2,

				'USER_ID'		=> $row['user_id'],
			));
		}
		$db->sql_freeresult($result);

		if ($user->data['user_type'] == USER_FOUNDER || $user->data['user_type'] == USER_NORMAL)
		{
			$sql = 'SELECT * FROM ' . CHAT_SESSIONS_TABLE . " WHERE user_id = {$user->data['user_id']}";
			$result = $db->sql_query($sql);
			$row = $db->sql_fetchrow($result);
			$db->sql_freeresult($result);

			if ($row['user_id'] != $user->data['user_id'])
			{
				$sql_ary = array(
					'user_id'			=> $user->data['user_id'],
					'username'			=> $user->data['username'],
					'user_colour'		=> $user->data['user_colour'],
					'user_login'		=> time(),
					'user_lastupdate'	=> time(),
				);
				$sql = 'INSERT INTO ' . CHAT_SESSIONS_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary);
				$db->sql_query($sql);
			}
			else
			{
				$sql_ary = array(
					'username'			=> $user->data['username'],
					'user_colour'		=> $user->data['user_colour'],
					'user_login'		=> time(),
					'user_lastupdate'	=> time(),
				);
				$sql = 'UPDATE ' . CHAT_SESSIONS_TABLE . ' SET ' . $db->sql_build_array('UPDATE', $sql_ary) . " WHERE user_id = {$user->data['user_id']}";
				$db->sql_query($sql);
			}
		}
		$chat->whois_online();
		$template->assign_vars(array(
			'TIME'	=> time(),
			'DELAY'	=> $default_delay,
		));
	break;

	case 'read':
		$sql = 'SELECT * FROM ' . CHAT_TABLE . '
			WHERE channel_id = ' . $channel_id . '
				AND message_id > ' . $last_id . '
				ORDER BY message_id DESC';
		$result = $db->sql_query_limit($sql, $chat_config['num_message_display']);
		$rows = $db->sql_fetchrowset($result);

		if (!sizeof($rows) && ((time() - 60) < $last_time))
		{
			exit;
		}
		foreach ($rows as $row)
		{
			if ($count++ == 0)
			{
				$last_id = $row['message_id'];
			}
			$template->assign_block_vars('chatrow', array(
				'MESSAGE_ID'	=> $row['message_id'],
				'USERNAME_FULL'	=> get_username_string('full', $row['user_id'], $row['username'], $row['user_colour'], $user->lang['GUEST']),
				'MESSAGE'		=> generate_text_for_display($row['message'], $row['bbcode_uid'], $row['bbcode_bitfield'], $row['bbcode_options']),
				'TIME'			=> $user->format_date($row['time']),
				'CLASS'			=> ($row['message_id'] % 2) ? 1 : 2,

				'USER_ID'		=> $row['user_id'],
			));
		}
		$db->sql_freeresult($result);
		if ((time() - 60) > $last_time)
		{
			$chat->whois_online();
			$sql_ary = array(
				'username'			=> $user->data['username'],
				'user_colour'		=> $user->data['user_colour'],
				'user_lastupdate'	=> time(),
			);
			$sql = 'UPDATE ' . CHAT_SESSIONS_TABLE . '
				SET ' . $db->sql_build_array('UPDATE', $sql_ary) . "
				WHERE user_id = {$user->data['user_id']}";
			$result = $db->sql_query($sql);
		}
		$get = true;
	break;

	case 'add':
		if (!$user->data['is_registered'] || $user->data['user_type'] == USER_INACTIVE || $user->data['user_type'] == USER_IGNORE)
		{
			redirect(append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=login'));
		}

		$get = true;
		$read_interval = request_var('read_interval', 0);
		$message = utf8_normalize_nfc(request_var('message', '', true));

		if (!$message)
		{
			break;
		}
		$message = str_replace('---', '- -', $message);
		$uid = $bitfield = $options = '';
		$allow_bbcode = $allow_urls = $allow_smilies = true;
		generate_text_for_storage($message, $uid, $bitfield, $options, $allow_bbcode, $allow_urls, $allow_smilies);

		$sql_ary = array(
			'chat_id'			=> 1,
			'channel_id'		=> $channel_id,
			'user_id'			=> $user->data['user_id'],
			'username'			=> $user->data['username'],
			'user_colour'		=> $user->data['user_colour'],
			'message'			=> $message,
			'bbcode_bitfield'	=> $bitfield,
			'bbcode_uid'		=> $uid,
			'bbcode_options'	=> $options,
			'time'				=> time(),
		);
		$sql = 'INSERT INTO ' . CHAT_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary);
		$db->sql_query($sql);

		$sql_ary = array(
			'username'			=> $user->data['username'],
			'user_colour'		=> $user->data['user_colour'],
			'user_lastpost'		=> time(),
			'user_lastupdate'	=> time(),
		);
		$sql = 'UPDATE ' . CHAT_SESSIONS_TABLE . ' SET ' . $db->sql_build_array('UPDATE', $sql_ary) . " WHERE user_id = {$user->data['user_id']}";
		$result = $db->sql_query($sql);


		$sql = 'SELECT * FROM ' . CHAT_TABLE . '
			WHERE channel_id = ' . $channel_id . '
				AND message_id > ' . $last_id . '
				ORDER BY message_id DESC';
		$result = $db->sql_query_limit($sql, $chat_config['num_message_display']);
		$rows = $db->sql_fetchrowset($result);

		if (!sizeof($rows) && ((time() - 60) < $last_time))
		{
			exit;
		}
		foreach ($rows as $row)
		{
			if ($count++ == 0)
			{
				$last_id = $row['message_id'];
			}
			$template->assign_block_vars('chatrow', array(
				'MESSAGE_ID'	=> $row['message_id'],
				'USERNAME_FULL'	=> get_username_string('full', $row['user_id'], $row['username'], $row['user_colour'], $user->lang['GUEST']),
				'MESSAGE'		=> generate_text_for_display($row['message'], $row['bbcode_uid'], $row['bbcode_bitfield'], $row['bbcode_options']),
				'TIME'			=> $user->format_date($row['time']),
				'CLASS'			=> ($row['message_id'] % 2) ? 1 : 2,

				'USER_ID'		=> $row['user_id'],
			));
		}
		$db->sql_freeresult($result);

		if ($read_interval != $delay['online'])
		{
			$chat->whois_online();
		}
	break;

	case 'smilies':
	    if (!$auth->acl_get('u_as_smilies'))
	    {
	        as_error($user->lang['NO_SMILIE_PERM']);
		}

		$sql = 'SELECT *
			FROM ' . SMILIES_TABLE .
				' WHERE display_on_posting = 1
			ORDER BY smiley_order';
		$result = $db->sql_query($sql);
		if ($result)
		{
			$num_smilies = 0;
			$rowset = array();
			$last_url = '';
			
			while ($row = $db->sql_fetchrow($result))
			{
				if ($row['smiley_url'] !== $last_url)
				{
					echo "<smilies>\n
						<code>" . xml($row['code']) . "</code>\n
						<img>" . xml($phpbb_root_path . $config['smilies_path'] . '/' . $row['smiley_url']) . "</img>\n
						<alt>" . xml($row['emotion']) . "</alt>\n
						</smilies>";
				}
				$last_url = $row['smiley_url'];
			}
			echo '</xml>';
			exit;
		}	
		else
		{
			as_sql_error($sql, __LINE__, __FILE__);
		}
	break;

	case 'delete':
		$get = true;
		$chat_id = request_var('chat_id', 0);

		if (!$chat_id)
		{
			break;
		}

		if (!$auth->acl_get('a_') && !$auth->acl_get('m_'))
		{
			break;
		}
		$sql = 'DELETE FROM ' . CHAT_TABLE . " WHERE message_id = $chat_id";
		$db->sql_query($sql);
	break;

	case 'ban':
		$get = true;
		$user_id = request_var('user_id', 0);

		if (!$user_id)
		{
			break;
		}

		if (!$auth->acl_get('a_') && !$auth->acl_get('m_'))
		{
			break;
		}
		$sql = 'UPDATE ' . USERS_TABLE . ' SET user_chat_banned = 1 WHERE user_id = ' . $user_id;
		$db->sql_query($sql);
	break;
}

// Begin smilie code (the name of the person who coded this escapes me. If this is your code, please contact me so I can put the credit here)
//Get the status of the following features
$bbcode_status	= ($config['allow_bbcode'] && $config['auth_bbcode_pm'] && $auth->acl_get('u_pm_bbcode')) ? true : false;
$smilies_status	= ($config['allow_smilies'] && $config['auth_smilies_pm'] && $auth->acl_get('u_pm_smilies')) ? true : false;
$img_status		= ($config['auth_img_pm'] && $auth->acl_get('u_pm_img')) ? true : false;
$flash_status	= ($config['auth_flash_pm'] && $auth->acl_get('u_pm_flash')) ? true : false;
$url_status		= ($config['allow_post_links']) ? true : false;

// Generate smiley listing
generate_smilies('inline', 0);

//Assign the features template variable
$template->assign_vars(array(
	'BBCODE_STATUS'			=> ($bbcode_status) ? sprintf($user->lang['BBCODE_IS_ON'], '<a href="' . append_sid("{$phpbb_root_path}faq.$phpEx", 'mode=bbcode') . '">', '</a>') : sprintf($user->lang['BBCODE_IS_OFF'], '<a href="' . append_sid("{$phpbb_root_path}faq.$phpEx", 'mode=bbcode') . '">', '</a>'),
	'IMG_STATUS'			=> ($img_status) ? $user->lang['IMAGES_ARE_ON'] : $user->lang['IMAGES_ARE_OFF'],
	'FLASH_STATUS'			=> ($flash_status) ? $user->lang['FLASH_IS_ON'] : $user->lang['FLASH_IS_OFF'],
	'SMILIES_STATUS'		=> ($smilies_status) ? $user->lang['SMILIES_ARE_ON'] : $user->lang['SMILIES_ARE_OFF'],
	'URL_STATUS'			=> ($url_status) ? $user->lang['URL_IS_ON'] : $user->lang['URL_IS_OFF'],				
	'S_COMPOSE_PM'			=> true,
	'S_BBCODE_ALLOWED'		=> $bbcode_status,
	'S_SMILIES_ALLOWED'		=> $smilies_status,
	'S_BBCODE_IMG'			=> $img_status,
	'S_BBCODE_FLASH'		=> $flash_status,
	'S_BBCODE_QUOTE'		=> false,
	'S_BBCODE_URL'			=> $url_status,
));

// Build custom bbcodes array
display_custom_bbcodes();
// End smilie code

if ($chat_config['channels_enabled'] == 1)
{
	$sql = 'SELECT * FROM ' . CHAT_CHANNELS_TABLE;
	$result = $db->sql_query($sql);

	while ($row = $db->sql_fetchrow($result))
	{
		$template->assign_block_vars('chan_select', array(
			'CHANNEL_ID'			=> $row['channel_id'],
			'CHANNEL_NAME'			=> $row['channel_name'],
			'CHANNEL_PASSWORD'		=> $row['channel_password'],
			'SELECTED'				=> ($channel_id == $row['channel_id']) ? true : false,

			'S_CHAN_HAS_PASSWORD'	=> (!empty($row['channel_password'])) ? true : false,
		));
	}
	$db->sql_freeresult($result);

	$self_php = str_replace('/', '', $chat_php);
	$template->assign_vars(array(
		'CHANNELS_ENABLED'	=> true,
		'S_SELECT_ACTION'	=> append_sid("{$phpbb_root_path}$self_php"),
	));
}

$mode = strtoupper($mode);
$template->assign_vars(array(
	'FILENAME'		=> append_sid("{$phpbb_root_path}chat.$phpEx"),
	'LAST_ID'		=> $last_id,
	'S_CHAT'		=> (!$get && $chat_php == '/chat.php') ? true : false,
	'S_GET_CHAT'	=> ($get && $chat_php == '/chat.php') ? true : false,
	'S_' . $mode	=> true,

	'S_CHAT_PHP'	=> ($chat_php == '/chat.php') ? true : false,
	'CHAT_CHANNEL_ID'	=> $channel_id,
));

if ($popup == true)
{
	$template->assign_vars(array(
		'S_CHAT_POPUP'	=> true,
	));
}

if ($chat_php == '/chat.php')
{
page_header($user->lang['PAGE_TITLE']);

//if ($popup == true)
//{
	$template->set_filenames(array(
		'body' => ($popup == true) ? 'chat_popup_body.html' : 'chat_body.html',
	));
/*}
else
{
	$template->set_filenames(array(
		'body' => 'chat_body.html'
	));
}*/

page_footer();
}

?>